// main js for Shift And Timings Tab.
//
// var tab2ViewModel = new Tab2ViewModel();
// function loadTab2Model() {
// //ko.applyBindings(tab2ViewModel);
// //ko.applyBindings(tab2ViewModel, document.getElementById('tabs-2'));
// }
//
// var tab1Activated = false;
// var tab2Activated = false;
// var tab3Activated = false;
// var tab4Activated = false;
// var tab5Activated = false;
// var selectedTabID = "tabs-1"
// $(document).ready(function() {
// $('#tabs').tabs({
// activate : function(e, ui) {
// var key = $(ui.newPanel).prop('id');
// console.log("key :: ", key)
//
// if (key == "tabs-2" && !tab2Activated) {
// ko.applyBindings(tab2ViewModel, document.getElementById('tabs-2'));
// tab2Activated = true;
//
// }
//
// if (key == "tabs-3" && !tab3Activated) {
// ko.applyBindings(new myNewFrameworkViewModel(), document.getElementById('tabs-3'));
// tab3Activated = true;
// }
//
// if (key == "tabs-4" && !tab4Activated) {
// ko.applyBindings(new myMainSubjectViewModel(), document.getElementById('tabs-4'));
// tab4Activated = true;
// }
//
// if (key == "tabs-5" && !tab5Activated) {
// ko.applyBindings(new myMainTab5ViewModel(), document.getElementById('tabs-5'));
// tab5Activated = true;
// }
//
// }
// });
//
//
// $('#tabs').tabs("option", "active", 1);
//
// $("#create-Shift").dialog({
// autoOpen : false,
// width : 600,
// height : 500,
// modal : true
// });
//
//
// });

function Tab2ViewModel() {
	var self = this;
	self.title = "Version New";
	self.windowMode = "";
	self.shiftArr = ko.observableArray([]);
	self.label = ko.observable('dialog test');
	self.isOpen = ko.observable(false);
	self.hasSchedules = ko.observable(false);

	/////////////////////////////////

	self.errorTitle = ko.observable();
	self.errorDesc = ko.observable();
	self.isErrorDialogOpen = ko.observable(false);

	self.openErrorDialog = function(myErrorTitle, myErrorDesc) {
		self.errorTitle(myErrorTitle);
		self.errorDesc(myErrorDesc);
		this.isErrorDialogOpen(true);

	};
	self.closeErrorDialog = function() {
		this.isErrorDialogOpen(false);
	};

	self.open = function() {
		console.log("self :: ", self.isOpen());
		this.isOpen(true);
	};
	self.close = function() {
		/**
		 * TODO: Create through open close
		 */
		$("#create-Shift").dialog("close");
		console.log("self self.close:: ", self.isOpen());
		this.isOpen(false);

	};
	self.cancelDeleteDialog = function() {
		$("#dialog-confirmShiftDelete").dialog("close");
	};
	self.closeShiftDialog = function() {
		console.log("self :: closeShiftDialog ========= ", self.isOpen());

		console.log("self :: ", self);
		console.log("this :: ", this);
		//	self.isOpen(false);
		$("#create-Shift").dialog("close");

	};

	self.selectedItem = ko.observable();
	//make edits to a copy
	self.itemForEditing = ko.observable();
	self.ShiftDialogTitle = ko.observable("ffd");

	self.init = function() {
		showLoader(true, TYPE_LOADING);

		loadShiftList();
		console.log("called init");
	};
	function loadShiftList() {
		var shiftTimingsJsonData = $.getJSON(baseOperationUrl + 'getSecShifts&sectionId=' + sectionId, {
			returnformat : 'json'
		}, function(allData) {
			var mappedData = jQuery.map(allData, function(item) {
				//  defaultData = allData[0];
				//console.log("defaultdata----xs--11------",defaultData)
				return new ShiftTimingsModel(item);
			});
			self.shiftArr(mappedData);

		});
		shiftTimingsJsonData.complete(function() {
			console.log("second complete loadSecClassTeachers");
			loadShiftTimingsDefaultJson();
		});
	}


	self.addShiftTimingsModel = function() {
		self.windowMode = "add";
		console.log("defaultdata---addShiftTimingsModel-----", defaultData);
		console.log("defaultData.schedules-----", defaultData.schedules);
		console.log("defaultData.grades-----", defaultData.grades);
		self.itemForEditing(new ShiftTimingsModel({
			shiftId : defaultData.shiftId,
			sectionId : defaultData.sectionId,
			shiftTitle : defaultData.shiftTitle,
			schedules : defaultData.schedules,
			grades : defaultData.grades
		}));
		self.ShiftDialogTitle("Create Shift");
		//$("#create-Shift").dialog("open");
		self.open();
	};

	self.openShiftTimingsForEditing = function(item) {
		console.log("openShiftTimingsForEditing");
		self.windowMode = "edit";
		self.selectItem(item);
		self.ShiftDialogTitle("Edit Shift");
		//$("#create-Shift").dialog("open");
		self.open();
	};
	self.openDeleteShiftTimingsDialog = function(item) {
		console.log("openDeleteGradeIndexDialog");
		self.selectedItem(item);
		$("#dialog-confirmShiftDelete").dialog("open");
	};
	self.deleteShiftTimings = function() {
		console.log("deleteShiftTimings", this.selectedItem().shiftId());
		deleteShiftTimingsFromServer(String(this.selectedItem().shiftId()));
		this.shiftArr.remove(this.selectedItem());
		$("#dialog-confirmShiftDelete").dialog("close");
	};

	self.saveShiftTimingsModel = function() {

		/**
		 *Validation
		 */
		var errorExists = false;
		var editedItem = self.itemForEditing();

		

		/**
		 *Check if one division checked
		 */
		var oneDivisionChecked = false;
		for (var i = 0; i < editedItem.grades().length; i++) {
			var gradesModel = editedItem.grades()[i];
			var isChecked = false;
			for (var j = 0; j < gradesModel.divisions().length; j++) {
				var division = gradesModel.divisions()[j];
				isChecked = division.isMapped();
				if (isChecked) {
					oneDivisionChecked = true;
					break;
				};

			};
			if (isChecked) {
				oneDivisionChecked = true;
				break;
			};
		};

		if (!oneDivisionChecked) {
			this.openErrorDialog("No Division Selected", "Please Select a Division before saving.");
			return;
			//returning the control providing user a chance to correct the issues
		}

		/**
		 *Check if > 4 divisions checked
		 */
		var maxDivisionsChecked = false;
		for (var i = 0; i < editedItem.grades().length; i++) {
			var gradesModel = editedItem.grades()[i];
			var isChecked = false;
			var divCount = 0;
			for (var j = 0; j < gradesModel.divisions().length; j++) {
				var division = gradesModel.divisions()[j];
				isChecked = division.isMapped();
				if (isChecked) {
					divCount++;
				};
				if (divCount > 4) {
					maxDivisionsChecked = true;
					break;
				};
			};
			if (maxDivisionsChecked) {
				maxDivisionsChecked = true;
				break;
			};
		};

		if (maxDivisionsChecked) {
			this.openErrorDialog("Maximimum Divisions Selected", "YYou can select maximum 4 divisions per class.");
			return;
			//returning the control providing user a chance to correct the issues
		}

		/**
		 *Check if one Schedule checked
		 */
		var oneScheduleChecked = false;
		for (var i = 0; i < editedItem.schedules().length; i++) {
			var schedulesModel = editedItem.schedules()[i];
			var isChecked = false;
			isChecked = Boolean(schedulesModel.isMapped());

			if (isChecked) {
				oneScheduleChecked = true;
				break;
			};
		};

		if (!oneScheduleChecked) {
			this.openErrorDialog("No Schedule Selected", "Please Select a Schedule before saving.");
			return;
			//returning the control providing user a chance to correct the issues
		}

		/**
		 *Check for Errors in the main Model
		 */
		if (editedItem.errors().length != 0) {
			//verifying the errors attribute using the count of errors
			editedItem.errors.showAllMessages(true);
			//displaying the corresponding error messages
			errorExists = true;
			//set error flag to stop further processing
		}

		if (errorExists) {
			this.openErrorDialog("Required Fields", "Please fill all Required fields before saving.");
			return;
			//returning the control providing user a chance to correct the issues
		}

		var mapping = {
			'ignore' : ["errors"]
		};

		var saveDataStr = ko.mapping.toJSON(self.itemForEditing(), mapping);

		if (self.windowMode == "add") {
			self.shiftArr.push(self.itemForEditing());
			//var saveDataStr = JSON.stringify(ko.toJS(self.itemForEditing()), null, 2);
			console.log("saveDataStr \n", saveDataStr);
			saveShiftTimingsToServer(saveDataStr);
		} else if (self.windowMode == "edit") {

			//var saveDataStr = JSON.stringify(ko.toJS(self.itemForEditing()), null, 2);
			console.log("saveDataStr \n", saveDataStr);
			self.acceptItem(null);
			saveShiftTimingsToServer(saveDataStr);
		} else {
			self.acceptItem(null);
		}
		$("#create-Shift").dialog("close");

		console.log("selfvv:: ", self);
		console.log("this vv:: ", this);

		self.itemForEditing(null);
	};

}

function ShiftTimingsModel(data) {
	var self = this;
	self.shiftId = ko.observable(data.shiftId);
	self.sectionId = ko.observable(data.sectionId);
	self.shiftTitle = ko.observable(data.shiftTitle).extend({
		required : {
			message : 'Required'
		}
	});

	self.schedules = ko.observableArray([]);
	self.grades = ko.observableArray([]);

	self.cache = function() {
	};
	self.update(data);
	console.log("self.sectionId", self.shiftId());

	self.errors = ko.validation.group(this, {
		deep : true
	});

}

function SchedulesModel(data) {
	var self = this;
	self.scheduleId = ko.observable(data.scheduleId);
	self.sectionId = ko.observable(data.sectionId);
	self.scheduleTitle = ko.observable(data.scheduleTitle);
	self.startTiming = ko.observable(data.startTiming);
	self.endTiming = ko.observable(data.endTiming);
	self.isMapped = ko.observable(data.isMapped);
	self.scheduleTitle.isSelected = ko.observable((self.isMapped() == 1));
	self.daysOfWeek = ko.observableArray([]);
	self.timeTable = ko.observable(data.timeTable);
	var mappedDaysOfWeekData = jQuery.map(data.daysOfWeek, function(item) {
		return new DaysOfWeekModel(item);
	});
	self.daysOfWeek(mappedDaysOfWeekData);
	var mappedTimeTableData = jQuery.map(data.timeTable, function(item) {
		return new TimeTableModel(item);
	});
	self.timeTable(mappedTimeTableData);
	self.timeTable.periodCount = ko.computed(function() {
		var counter = 0;
		var incrementCtr = ko.utils.arrayMap(self.timeTable(), function(item) {
			if (item.type() == "Period") {
				bool = counter++;
			}
		});
		return counter;
	}, self);
	self.timeTable.breakCount = ko.computed(function() {
		var counter = 0;
		var incrementCtr = ko.utils.arrayMap(self.timeTable(), function(item) {
			if (item.type() == "Break") {
				bool = counter++;
			}
		});
		return counter;
	}, self);
	self.scheduleTitle.isSelected.subscribe(function(bool) {
		console.log(bool);
		if (bool) {
			self.isMapped(1);
		} else {
			self.isMapped(0);
		}
		console.log("this.isMapped  ", self.isMapped());
	});

}

function GradesModel(data) {
	this.gradeTitle = ko.observable(data.gradeTitle);
	this.ceGradeId = ko.observable(data.ceGradeId);
	this.divisions = ko.observableArray([]);
	this.gradeTitle.isMapped = ko.computed(function() {
		var bool = 0;
		var ismaped = ko.utils.arrayMap(this.divisions(), function(item) {
			if (item.isMapped() == 1) {
				bool = 1;
			}
		});
		return bool;
	}, this);

	var mappedDivisionData = jQuery.map(data.divisions, function(item) {
		return new DivisionsModel(item);
	});
	this.divisions(mappedDivisionData);

}

function DaysOfWeekModel(data) {
	this.day = ko.observable(data.day);
}

function TimeTableModel(data) {
	this.type = ko.observable(data.type);
}

function DivisionsModel(data) {
	var self = this;

	self.classId = ko.observable(data.classId);
	self.divisionTitle = ko.observable(data.divisionTitle);
	self.isMapped = ko.observable(data.isMapped);
	self.divisionTitle.isSelected = ko.observable((self.isMapped() == 1));

	self.classId.isDisabled = ko.computed(function() {
		/**
		 *Check if common class checked
		 */
		var oneDivisionIsThere = false;
		for (var s = 0; s < tab2ShiftViewModel.shiftArr().length; s++) {
			var editedItem = tab2ShiftViewModel.shiftArr()[s];
			for (var i = 0; i < editedItem.grades().length; i++) {
				var gradesModel = editedItem.grades()[i];
				var isChecked = false;
				for (var j = 0; j < gradesModel.divisions().length; j++) {
					var division = gradesModel.divisions()[j];
					isChecked = division.isMapped();
					var isDifferentShift = false;
					if (tab2ShiftViewModel.itemForEditing()) {
						isDifferentShift = editedItem.shiftId() != tab2ShiftViewModel.itemForEditing().shiftId();
					}

					if (isChecked && division.classId() == self.classId() && isDifferentShift) {
						oneDivisionIsThere = true;
						break;
					};

				};
				if (oneDivisionIsThere) {
					break;
				};
			};
			if (oneDivisionIsThere) {
				break;
			};
		};
		console.log("self.divisionTitle() :: ", self.divisionTitle(), " : ", oneDivisionIsThere);
		return oneDivisionIsThere;
	}, self);

	self.divisionTitle.isSelected.subscribe(function(bool) {
		console.log(bool);
		if (bool) {
			self.isMapped(1);
		} else {
			self.isMapped(0);
		}
		console.log("this.isMapped  ", self.isMapped());

	});

}

ko.utils.extend(ShiftTimingsModel.prototype, {
	update : function(data) {
		this.shiftId(data.shiftId || "");
		this.sectionId(data.sectionId || "");
		this.shiftTitle(data.shiftTitle || "");

		var mappedSchedulesData = jQuery.map(data.schedules, function(item) {
			return new SchedulesModel(item);
		});
		this.schedules(mappedSchedulesData);
		var mappedgradesData = jQuery.map(data.grades, function(item) {
			return new GradesModel(item);
		});
		this.grades(mappedgradesData);

		//save off the latest data for later use
		this.cache.latestData = data;
	},
	revert : function() {
		this.update(this.cache.latestData);
	}
});

ko.utils.extend(Tab2ViewModel.prototype, {
	//select an item and make a copy of it for editing
	selectItem : function(item) {
		console.log("::selectItem::", item);
		this.selectedItem(item);
		this.itemForEditing(new ShiftTimingsModel(ko.toJS(item)));
	},

	acceptItem : function(item) {
		var selected = this.selectedItem(), edited = ko.toJS(this.itemForEditing());
		//clean copy of edited

		//apply updates from the edited item to the selected item
		selected.update(edited);
		//clear selected item
		this.selectedItem(null);
		this.itemForEditing(null);
	},

	//just throw away the edited item and clear the selected observables
	revertItem : function() {
		this.close();
		this.selectedItem(null);
		this.itemForEditing(null);
	},
});

ko.bindingHandlers.uniqueId = {
	init : function(element, valueAccessor) {
		var value = valueAccessor();
		value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);

		element.id = value.id;
	},
	counter : 0,
	prefix : "unique"
};

ko.bindingHandlers.uniqueFor = {
	init : function(element, valueAccessor) {
		var value = valueAccessor();
		value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);

		element.setAttribute("for", value.id);
	}
};

